<template>
  <div class="container mx-auto px-4 py-6">
    <!-- 页面标题 -->
    <h1 class="text-2xl font-bold text-gray-800 mb-6">教师管理系统</h1>
    
    <!-- 查询条件区域 -->
    <div class="query-area bg-white rounded-lg shadow-md p-4 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div class="form-group">
          <label for="departmentId" class="block text-sm font-medium text-gray-700 mb-1">部门</label>
          <select 
            id="departmentId" 
            v-model="queryParams.departmentId" 
            class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          >
            <option value="">全部</option>
            <option v-for="dept in departments" :key="dept.id" :value="dept.id">{{ dept.name }}</option>
          </select>
        </div>
        
        <div class="form-group">
          <label for="positionId" class="block text-sm font-medium text-gray-700 mb-1">职务</label>
          <select 
            id="positionId" 
            v-model="queryParams.positionId" 
            class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          >
            <option value="">全部</option>
            <option v-for="position in positions" :key="position.id" :value="position.id">{{ position.name }}</option>
          </select>
        </div>
        
        <div class="form-group">
          <label for="titleId" class="block text-sm font-medium text-gray-700 mb-1">职称</label>
          <select 
            id="titleId" 
            v-model="queryParams.titleId" 
            class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          >
            <option value="">全部</option>
            <option v-for="title in titles" :key="title.id" :value="title.id">{{ title.name }}</option>
          </select>
        </div>
      </div>
      
      <div class="flex justify-end mt-4">
        <button @click="resetQuery" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-colors mr-2">
          重置
        </button>
        <button @click="fetchTeachers" class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-md transition-colors">
          <i class="fa fa-search mr-2"></i>查询
        </button>
      </div>
    </div>
    
    <!-- 操作区域：新增 -->
    <div class="action-bar bg-white rounded-lg shadow-md p-4 mb-6 flex justify-end">
      <button @click="openAddModal" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md transition-colors flex items-center">
        <i class="fa fa-plus mr-2"></i>新增教师
      </button>
    </div>
    
    <!-- 教师表格 -->
    <div class="table-container w-full bg-white rounded-lg shadow-md overflow-hidden">
      <table class="teacher-table w-full">
        <thead>
          <tr class="bg-gray-50">
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">工号</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">姓名</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">性别</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">部门</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-200">
          <tr v-for="teacher in teachers" :key="teacher.id" class="hover-row hover:bg-gray-50 transition-colors">
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ teacher.id }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ teacher.employeeId }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ teacher.name }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ teacher.gender === 1 ? '男' : '女' }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ getDepartmentName(teacher.departmentId) }}</td>
            <td class="px-6 py-4 whitespace-nowrap text-sm">
              <span :class="getStatusClass(teacher.status)">{{ getStatusText(teacher.status) }}</span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
              <button 
                @click="openViewModal(teacher.id)" 
                class="text-blue-500 hover:text-blue-700 transition-colors mr-3"
              >
                <i class="fa fa-eye mr-1"></i>查看
              </button>
              <button 
                @click="openEditModal(teacher.id)" 
                class="text-green-500 hover:text-green-700 transition-colors mr-3"
              >
                <i class="fa fa-pencil mr-1"></i>编辑
              </button>
              <button 
                @click="deleteTeacher(teacher.id)" 
                class="text-red-500 hover:text-red-700 transition-colors"
              >
                <i class="fa fa-trash mr-1"></i>删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <!-- 空状态提示 -->
    <div v-if="teachers.length === 0" class="empty-state w-full bg-white rounded-lg shadow-md p-8 text-center">
      <div class="empty-icon text-6xl text-gray-400 mb-4">
        <i class="fa fa-folder-open-o"></i>
      </div>
      <p class="text-gray-600 mb-4">暂无教师数据</p>
      <button @click="openAddModal" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md transition-colors">
        <i class="fa fa-plus mr-2"></i>添加教师
      </button>
    </div>
    
    <!-- 查看、新增、编辑教师模态框 -->
    <div v-if="showViewModal || showAddModal || showEditModal" class="modal-overlay fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="modal-content bg-white rounded-lg shadow-xl w-full max-w-4xl transform transition-all">
        <div class="modal-header flex justify-between items-center p-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">
            {{ showViewModal ? '查看教师' : (showEditModal ? '编辑教师' : '新增教师') }}
          </h3>
          <button @click="closeModal" class="text-gray-400 hover:text-gray-600">
            <i class="fa fa-times"></i>
          </button>
        </div>
        
        <div class="modal-body p-4">
          <!-- 基本信息 -->
          <div class="mb-6">
            <h4 class="text-base font-medium text-gray-900 mb-4 flex items-center">
              <span class="inline-block w-2 h-2 bg-blue-500 rounded-full mr-2"></span>
              基本信息
            </h4>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div class="form-group">
                <label for="employeeId" class="block text-sm font-medium text-gray-700 mb-1">工号</label>
                <input 
                  type="text" 
                  id="employeeId" 
                  v-model="currentTeacher.employeeId" 
                  class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  :disabled="showViewModal || showEditModal"
                >
                <p v-if="errors.employeeId" class="mt-1 text-red-500 text-sm">{{ errors.employeeId }}</p>
              </div>
              
              <div class="form-group">
                <label for="name" class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                <input 
                  type="text" 
                  id="name" 
                  v-model="currentTeacher.name" 
                  class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  :disabled="showViewModal"
                >
                <p v-if="errors.name" class="mt-1 text-red-500 text-sm">{{ errors.name }}</p>
              </div>
              
              <div class="form-group">
                <label for="gender" class="block text-sm font-medium text-gray-700 mb-1">性别</label>
                <select 
                  id="gender" 
                  v-model.number="currentTeacher.gender" 
                  class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  :disabled="showViewModal"
                >
                <option value="">请选择性别</option>
                  <option value="1">男</option>
                  <option value="2">女</option>
                </select>
                <p v-if="errors.gender" class="mt-1 text-red-500 text-sm">{{ errors.gender }}</p>
              </div>
              
              <div class="form-group">
                <label for="birthDate" class="block text-sm font-medium text-gray-700 mb-1">出生日期</label>
                <input 
                  type="date" 
                  id="birthDate" 
                  v-model="currentTeacher.birthDate" 
                  class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  :disabled="showViewModal"
                >
                <p v-if="errors.birthDate" class="mt-1 text-red-500 text-sm">{{ errors.birthDate }}</p>
              </div>
              
              <div class="form-group">
                <label for="phone" class="block text-sm font-medium text-gray-700 mb-1">手机号码</label>
                <input 
                  type="tel" 
                  id="phone" 
                  v-model="currentTeacher.phone" 
                  class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  :disabled="showViewModal"
                >
                <p v-if="errors.phone" class="mt-1 text-red-500 text-sm">{{ errors.phone }}</p>
              </div>
              
              <div class="form-group">
                <label for="email" class="block text-sm font-medium text-gray-700 mb-1">电子邮箱</label>
                <input 
                  type="email" 
                  id="email" 
                  v-model="currentTeacher.email" 
                  class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  :disabled="showViewModal"
                >
                <p v-if="errors.email" class="mt-1 text-red-500 text-sm">{{ errors.email }}</p>
              </div>
              
              <div class="form-group">
                <label for="departmentId" class="block text-sm font-medium text-gray-700 mb-1">部门</label>
                <select 
                  id="departmentId" 
                  v-model.number="currentTeacher.departmentId" 
                  class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  :disabled="showViewModal"
                >
                  <option value="">请选择部门</option>
                  <option v-for="dept in departments" :key="dept.id" :value="dept.id">{{ dept.name }}</option>
                </select>
                <p v-if="errors.departmentId" class="mt-1 text-red-500 text-sm">{{ errors.departmentId }}</p>
              </div>
              
              <div class="form-group">
                <label for="titleId" class="block text-sm font-medium text-gray-700 mb-1">职称</label>
                <select 
                  id="titleId" 
                  v-model.number="currentTeacher.titleId" 
                  class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  :disabled="showViewModal"
                >
                  <option value="">请选择职称</option>
                  <option v-for="title in titles" :key="title.id" :value="title.id">{{ title.name }}</option>
                </select>
                <p v-if="errors.titleId" class="mt-1 text-red-500 text-sm">{{ errors.titleId }}</p>
              </div>
              
              <div class="form-group">
                <label for="positionId" class="block text-sm font-medium text-gray-700 mb-1">职务</label>
                <select 
                  id="positionId" 
                  v-model.number="currentTeacher.positionId" 
                  class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  :disabled="showViewModal"
                >
                  <option value="">请选择职务</option>
                  <option v-for="position in positions" :key="position.id" :value="position.id">{{ position.name }}</option>
                </select>
                <p v-if="errors.positionId" class="mt-1 text-red-500 text-sm">{{ errors.positionId }}</p>
              </div>
              
              <div class="form-group">
                <label for="status" class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                <select 
                  id="status" 
                  v-model.number="currentTeacher.status" 
                  class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  :disabled="showViewModal"
                >
                  <option value="">请选择状态</option>
                  <option value="1">在职</option>
                  <option value="2">休假</option>
                  <option value="3">离职</option>
                </select>
                <p v-if="errors.status" class="mt-1 text-red-500 text-sm">{{ errors.status }}</p>
              </div>
              
              <div class="form-group">
                <label for="entryDate" class="block text-sm font-medium text-gray-700 mb-1">入职日期</label>
                <input 
                  type="date" 
                  id="entryDate" 
                  v-model="currentTeacher.entryDate" 
                  class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  :disabled="showViewModal"
                >
                <p v-if="errors.entryDate" class="mt-1 text-red-500 text-sm">{{ errors.entryDate }}</p>
              </div>
            </div>
          </div>
          
          <!-- 教育经历 -->
          <div class="mb-6">
            <div class="flex justify-between items-center mb-4">
              <h4 class="text-base font-medium text-gray-900 flex items-center">
                <span class="inline-block w-2 h-2 bg-green-500 rounded-full mr-2"></span>
                教育经历
              </h4>
              <button 
                v-if="!showViewModal" 
                @click="addEducation" 
                class="text-sm text-green-600 hover:text-green-700 flex items-center"
              >
                <i class="fa fa-plus-circle mr-1"></i>添加经历
              </button>
            </div>
            
            <div class="education-list space-y-4">
              <div 
                v-for="(education, index) in currentTeacher.educations" 
                :key="education.id || `temp-${index}`"
                class="bg-gray-50 p-4 rounded-lg relative"
              >
                <button 
                  v-if="!showViewModal" 
                  @click="removeEducation(index)" 
                  class="absolute top-2 right-2 text-red-500 hover:text-red-700"
                >
                  <i class="fa fa-times"></i>
                </button>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div class="form-group">
                    <label class="block text-sm font-medium text-gray-700 mb-1">学校</label>
                    <input 
                      type="text" 
                      v-model="education.school" 
                      class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      :disabled="showViewModal"
                    >
                  </div>
                  
                  <div class="form-group">
                    <label class="block text-sm font-medium text-gray-700 mb-1">专业</label>
                    <input 
                      type="text" 
                      v-model="education.major" 
                      class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      :disabled="showViewModal"
                    >
                  </div>
                  
                  <div class="form-group">
                    <label class="block text-sm font-medium text-gray-700 mb-1">学历</label>
                    <select 
                      v-model.number="education.degree" 
                      class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      :disabled="showViewModal"
                    >
                      <option value="">请选择学历</option>
                      <option value="1">高中</option>
                      <option value="2">专科</option>
                      <option value="3">本科</option>
                      <option value="4">硕士</option>
                      <option value="5">博士</option>
                      <option value="6">博士后</option>
                    </select>
                  </div>
                  
                  <div class="form-group">
                    <label class="block text-sm font-medium text-gray-700 mb-1">入学年份</label>
                    <input 
                      type="number" 
                      v-model="education.startYear" 
                      min="1900" 
                      max="2099"
                      class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      :disabled="showViewModal"
                    >
                  </div>
                  
                  <div class="form-group md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700 mb-1">毕业年份</label>
                    <input 
                      type="number" 
                      v-model="education.endYear" 
                      min="1900" 
                      max="2099"
                      class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      :disabled="showViewModal"
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 家庭关系 -->
          <div>
            <div class="flex justify-between items-center mb-4">
              <h4 class="text-base font-medium text-gray-900 flex items-center">
                <span class="inline-block w-2 h-2 bg-purple-500 rounded-full mr-2"></span>
                家庭关系
              </h4>
              <button 
                v-if="!showViewModal" 
                @click="addFamily" 
                class="text-sm text-purple-600 hover:text-purple-700 flex items-center"
              >
                <i class="fa fa-plus-circle mr-1"></i>添加关系
              </button>
            </div>
            
            <div class="family-list space-y-4">
              <div 
                v-for="(family, index) in currentTeacher.families" 
                :key="family.id || `temp-${index}`"
                class="bg-gray-50 p-4 rounded-lg relative"
              >
                <button 
                  v-if="!showViewModal" 
                  @click="removeFamily(index)" 
                  class="absolute top-2 right-2 text-red-500 hover:text-red-700"
                >
                  <i class="fa fa-times"></i>
                </button>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div class="form-group">
                    <label class="block text-sm font-medium text-gray-700 mb-1">关系</label>
                    <select 
                      v-model.number="family.relationship" 
                      class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      :disabled="showViewModal"
                    >
                      <option value="">请选择关系</option>
                      <option value="1">父亲</option>
                      <option value="2">母亲</option>
                      <option value="3">配偶</option>
                      <option value="4">子女</option>
                      <option value="5">兄弟姐妹</option>
                      <option value="6">其他</option>
                    </select>
                  </div>
                  
                  <div class="form-group">
                    <label class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                    <input 
                      type="text" 
                      v-model="family.name" 
                      class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      :disabled="showViewModal"
                    >
                  </div>
                  
                  <div class="form-group">
                    <label class="block text-sm font-medium text-gray-700 mb-1">联系电话</label>
                    <input 
                      type="tel" 
                      v-model="family.phone" 
                      class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      :disabled="showViewModal"
                    >
                  </div>
                  
                  <div class="form-group md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700 mb-1">工作单位</label>
                    <input 
                      type="text" 
                      v-model="family.workUnit" 
                      class="form-control w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      :disabled="showViewModal"
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="modal-footer flex justify-end p-4 border-t border-gray-200">
          <button @click="closeModal" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-colors">
            关闭
          </button>
          <button 
            v-if="showEditModal || showAddModal"
            @click="saveTeacher" 
            class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-md transition-colors"
          >
            保存
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'

// 状态管理
const teachers = ref([])
const departments = ref([])
const positions = ref([])
const titles = ref([])
const queryParams = ref({
  departmentId: '',
  positionId: '',
  titleId: ''
})
const showViewModal = ref(false)
const showAddModal = ref(false)
const showEditModal = ref(false)
const currentTeacher = ref({
  id: null,
  employeeId: '',
  name: '',
  gender: null,
  birthDate: '',
  phone: '',
  email: '',
  departmentId: null,
  titleId: null,
  positionId: null,
  status: null,
  entryDate: '',
  educations: [],
  families: []
})
const errors = ref({})
const isLoading = ref(false)

// 生命周期钩子：页面加载时获取初始数据
onMounted(() => {
  fetchInitialData()
})

// 获取初始数据（部门、职务、职称、教师列表）
const fetchInitialData = async () => {
  try {
    // 并行获取部门、职务和职称数据
    const [deptRes, positionRes, titleRes] = await Promise.all([
      fetch('/api/dept'),
      fetch('/api/job-position'),
      fetch('/api/title')
    ])
    
    const [deptData, positionData, titleData] = await Promise.all([
      deptRes.json(),
      positionRes.json(),
      titleRes.json()
    ])
    
    if (deptRes.ok && deptData.code === 200) {
      departments.value = deptData.data || []
    }
    
    if (positionRes.ok && positionData.code === 200) {
      positions.value = positionData.data || []
    }
    
    if (titleRes.ok && titleData.code === 200) {
      titles.value = titleData.data || []
    }
    
    // 获取教师列表
    fetchTeachers()
  } catch (error) {
    alert(`获取初始化数据失败：${error.message}`)
    console.error('获取初始化数据失败:', error)
  }
}

// 获取教师列表
const fetchTeachers = async () => {
  isLoading.value = true
  try {
    let url = '/api/teacher?'
    
    // 构建查询参数
    if (queryParams.value.departmentId) {
      url += `departmentId=${queryParams.value.departmentId}&`
    }
    if (queryParams.value.positionId) {
      url += `positionId=${queryParams.value.positionId}&`
    }
    if (queryParams.value.titleId) {
      url += `titleId=${queryParams.value.titleId}&`
    }
    
    // 去掉最后的&符号
    if (url.endsWith('&')) {
      url = url.slice(0, -1)
    }
    
    const response = await fetch(url)
    const data = await response.json()
    
    if (response.ok && data.code === 200) {
      teachers.value = data.data || []
    } else {
      throw new Error(data.msg || '请求失败')
    }
  } catch (error) {
    alert(`获取教师数据失败：${error.message}`)
    console.error('获取教师数据失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 重置查询条件
const resetQuery = () => {
  queryParams.value = {
    departmentId: '',
    positionId: '',
    titleId: ''
  }
}

// 获取部门名称
const getDepartmentName = (id) => {
  if (!id) return '-'
  const dept = departments.value.find(dept => dept.id === id)
  return dept ? dept.name : '-'
}

// 获取职务名称
const getPositionName = (id) => {
  if (!id) return '-'
  const position = positions.value.find(pos => pos.id === id)
  return position ? position.name : '-'
}

// 获取职称名称
const getTitleName = (id) => {
  if (!id) return '-'
  const title = titles.value.find(t => t.id === id)
  return title ? title.name : '-'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '在职',
    2: '休假',
    3: '离职'
  }
  return statusMap[status] || '-'
}

// 获取状态样式类
const getStatusClass = (status) => {
  const statusClassMap = {
    1: 'px-2 py-1 text-xs font-medium bg-green-100 text-green-800 rounded-full',
    2: 'px-2 py-1 text-xs font-medium bg-yellow-100 text-yellow-800 rounded-full',
    3: 'px-2 py-1 text-xs font-medium bg-red-100 text-red-800 rounded-full'
  }
  return statusClassMap[status] || 'px-2 py-1 text-xs font-medium bg-gray-100 text-gray-800 rounded-full'
}

// 表单验证
const validateForm = () => {
  const newErrors = {}
  
  if (!currentTeacher.value.employeeId.trim()) {
    newErrors.employeeId = '请输入工号'
  }
  
  if (!currentTeacher.value.name.trim()) {
    newErrors.name = '请输入姓名'
  }
  
  if (currentTeacher.value.gender === null || currentTeacher.value.gender === '') {
    newErrors.gender = '请选择性别'
  }
  
  if (!currentTeacher.value.departmentId) {
    newErrors.departmentId = '请选择部门'
  }
  
  if (!currentTeacher.value.titleId) {
    newErrors.titleId = '请选择职称'
  }
  
  if (!currentTeacher.value.positionId) {
    newErrors.positionId = '请选择职务'
  }
  
  if (currentTeacher.value.status === null || currentTeacher.value.status === '') {
    newErrors.status = '请选择状态'
  }
  
  // 简单的手机号码验证
  if (currentTeacher.value.phone && !/^1[3-9]\d{9}$/.test(currentTeacher.value.phone)) {
    newErrors.phone = '请输入有效的手机号码'
  }
  
  // 简单的邮箱验证
  if (currentTeacher.value.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(currentTeacher.value.email)) {
    newErrors.email = '请输入有效的电子邮箱'
  }
  
  // 出生日期验证
  if (currentTeacher.value.birthDate) {
    const birthDate = new Date(currentTeacher.value.birthDate)
    const today = new Date()
    if (birthDate > today) {
      newErrors.birthDate = '出生日期不能晚于今天'
    }
  }
  
  // 入职日期验证
  if (currentTeacher.value.entryDate) {
    const entryDate = new Date(currentTeacher.value.entryDate)
    const today = new Date()
    if (entryDate > today) {
      newErrors.entryDate = '入职日期不能晚于今天'
    }
    
    // 如果有出生日期，入职日期不能早于出生日期
    if (currentTeacher.value.birthDate) {
      const birthDate = new Date(currentTeacher.value.birthDate)
      if (entryDate < birthDate) {
        newErrors.entryDate = '入职日期不能早于出生日期'
      }
    }
  }
  
  // 验证教育经历
  if (currentTeacher.value.educations.length > 0) {
    currentTeacher.value.educations.forEach((edu, index) => {
      if (!edu.school) {
        newErrors[`education_${index}_school`] = '请输入学校名称'
      }
      
      if (!edu.major) {
        newErrors[`education_${index}_major`] = '请输入专业名称'
      }
      
      if (edu.degree === null || edu.degree === '') {
        newErrors[`education_${index}_degree`] = '请选择学历'
      }
      
      if (!edu.startYear) {
        newErrors[`education_${index}_startYear`] = '请输入入学年份'
      } else if (isNaN(edu.startYear) || edu.startYear < 1900 || edu.startYear > new Date().getFullYear()) {
        newErrors[`education_${index}_startYear`] = '请输入有效的入学年份'
      }
      
      if (!edu.endYear) {
        newErrors[`education_${index}_endYear`] = '请输入毕业年份'
      } else if (isNaN(edu.endYear) || edu.endYear < 1900 || edu.endYear > new Date().getFullYear()) {
        newErrors[`education_${index}_endYear`] = '请输入有效的毕业年份'
      } else if (edu.startYear && edu.endYear <= edu.startYear) {
        newErrors[`education_${index}_endYear`] = '毕业年份必须晚于入学年份'
      }
    })
  } else {
    newErrors.educations = '至少需要添加一条教育经历'
  }
  
  // 验证家庭关系
  if (currentTeacher.value.families.length > 0) {
    currentTeacher.value.families.forEach((family, index) => {
      if (family.relationship === null || family.relationship === '') {
        newErrors[`family_${index}_relationship`] = '请选择关系'
      }
      
      if (!family.name) {
        newErrors[`family_${index}_name`] = '请输入姓名'
      }
      
      if (!family.phone) {
        newErrors[`family_${index}_phone`] = '请输入联系电话'
      } else if (!/^1[3-9]\d{9}$/.test(family.phone)) {
        newErrors[`family_${index}_phone`] = '请输入有效的手机号码'
      }
    })
  } else {
    newErrors.families = '至少需要添加一条家庭关系'
  }
  
  errors.value = newErrors
  return Object.keys(newErrors).length === 0
}
  
// 添加新的教育经历
const addEducation = () => {
  currentTeacher.value.educations.push({
    id: null,
    teacherId: currentTeacher.value.id,
    school: '',
    major: '',
    degree: null,
    startYear: '',
    endYear: ''
  })
}
  
// 移除教育经历
const removeEducation = (index) => {
  if (confirm('确定要删除这条教育经历吗？')) {
    currentTeacher.value.educations.splice(index, 1)
  }
}
  
// 添加新的家庭关系
const addFamily = () => {
  currentTeacher.value.families.push({
    id: null,
    teacherId: currentTeacher.value.id,
    relationship: null,
    name: '',
    phone: '',
    workUnit: ''
  })
}
  
// 移除家庭关系
const removeFamily = (index) => {
  if (confirm('确定要删除这条家庭关系吗？')) {
    currentTeacher.value.families.splice(index, 1)
  }
}
  
// 打开查看模态框
const openViewModal = (id) => {
  fetch(`/api/teacher/${id}`)
    .then(response => response.json())
    .then(data => {
      if (data.code === 200) {
        // 确保日期格式正确
        const teacherData = {
          ...data.data,
          birthDate: data.data.birthDate ? new Date(data.data.birthDate).toISOString().split('T')[0] : '',
          entryDate: data.data.entryDate ? new Date(data.data.entryDate).toISOString().split('T')[0] : ''
        }
        
        // 获取教育经历
        fetch(`/api/education?teacherId=${id}`)
          .then(res => res.json())
          .then(eduData => {
            if (eduData.code === 200) {
              teacherData.educations = eduData.data || []
            }
            
            // 获取家庭关系
            fetch(`/api/family?teacherId=${id}`)
              .then(res => res.json())
              .then(familyData => {
                if (familyData.code === 200) {
                  teacherData.families = familyData.data || []
                }
                
                currentTeacher.value = teacherData
                showViewModal.value = true
                showAddModal.value = false
                showEditModal.value = false
              })
          })
      } else {
        throw new Error(data.msg || '获取教师信息失败')
      }
    })
    .catch(error => {
      alert(`获取教师信息失败：${error.message}`)
      console.error('获取教师信息失败:', error)
    })
}
  
// 打开新增模态框
const openAddModal = () => {
  // 重置表单数据和错误
  currentTeacher.value = {
    id: null,
    employeeId: '',
    name: '',
    gender: null,
    birthDate: '',
    phone: '',
    email: '',
    departmentId: null,
    titleId: null,
    positionId: null,
    status: null,
    entryDate: '',
    educations: [
      {
        id: null,
        teacherId: null,
        school: '',
        major: '',
        degree: null,
        startYear: '',
        endYear: ''
      }
    ],
    families: [
      {
        id: null,
        teacherId: null,
        relationship: null,
        name: '',
        phone: '',
        workUnit: ''
      }
    ]
  }
  errors.value = {}
  showViewModal.value = false
  showAddModal.value = true
  showEditModal.value = false
}
  
// 打开编辑模态框
const openEditModal = (id) => {
  fetch(`/api/teacher/${id}`)
    .then(response => response.json())
    .then(data => {
      if (data.code === 200) {
        // 确保日期格式正确
        const teacherData = {
          ...data.data,
          birthDate: data.data.birthDate ? new Date(data.data.birthDate).toISOString().split('T')[0] : '',
          entryDate: data.data.entryDate ? new Date(data.data.entryDate).toISOString().split('T')[0] : ''
        }
        
        // 获取教育经历
        fetch(`/api/education?teacherId=${id}`)
          .then(res => res.json())
          .then(eduData => {
            if (eduData.code === 200) {
              teacherData.educations = eduData.data || []
            }
            
            // 获取家庭关系
            fetch(`/api/family?teacherId=${id}`)
              .then(res => res.json())
              .then(familyData => {
                if (familyData.code === 200) {
                  teacherData.families = familyData.data || []
                }
                
                currentTeacher.value = teacherData
                errors.value = {}
                showViewModal.value = false
                showAddModal.value = false
                showEditModal.value = true
              })
          })
      } else {
        throw new Error(data.msg || '获取教师信息失败')
      }
    })
    .catch(error => {
      alert(`获取教师信息失败：${error.message}`)
      console.error('获取教师信息失败:', error)
    })
}
  
// 关闭模态框
const closeModal = () => {
  showViewModal.value = false
  showAddModal.value = false
  showEditModal.value = false
}
  
// 保存教师信息（新增或编辑）
const saveTeacher = async () => {
  // 清空之前的错误
  errors.value = {}
  
  // 表单验证
  if (!validateForm()) {
    console.log('表单验证失败:', errors.value)
    // 滚动到第一个错误字段
    const firstErrorField = document.querySelector('.text-red-500')
    if (firstErrorField) {
      firstErrorField.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
    return
  }
  
  try {
    // 准备教师DTO数据
    const teacherDTO = {
      employeeId: currentTeacher.value.employeeId,
      name: currentTeacher.value.name,
      gender: currentTeacher.value.gender,
      birthDate: currentTeacher.value.birthDate,
      phone: currentTeacher.value.phone,
      email: currentTeacher.value.email,
      departmentId: currentTeacher.value.departmentId,
      titleId: currentTeacher.value.titleId,
      positionId: currentTeacher.value.positionId,
      status: currentTeacher.value.status,
      entryDate: currentTeacher.value.entryDate,
      educations: currentTeacher.value.educations,
      families: currentTeacher.value.families
    }
    
    // 打印请求数据用于调试
    console.log('准备发送的数据:', teacherDTO)
    
    let response
    if (showAddModal.value) {
      // 新增教师
      console.log('发送POST请求到 /api/teacher')
      response = await fetch('/api/teacher', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(teacherDTO)
      })
    } else {
      // 编辑教师
      console.log(`发送PUT请求到 /api/teacher/${currentTeacher.value.id}`)
      response = await fetch(`/api/teacher/${currentTeacher.value.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(teacherDTO)
      })
    }
    
    // 检查HTTP状态码
    if (!response.ok) {
      throw new Error(`HTTP错误! 状态码: ${response.status}`)
    }
    
    const data = await response.json()
    
    // 打印响应数据
    console.log('服务器响应:', data)
    
    if (data.code === 200) {
      alert(showAddModal.value ? '教师添加成功' : '教师信息更新成功')
      closeModal()
      fetchTeachers() // 重新获取数据
    } else {
      throw new Error(data.msg || (showAddModal.value ? '添加失败' : '更新失败'))
    }
  } catch (error) {
    // 更详细的错误处理
    console.error('保存失败:', error)
    
    // 显示用户友好的错误信息
    alert(`操作失败: ${error.message}`)
  }
}
  
// 删除教师
const deleteTeacher = async (id) => {
  if (!confirm('确定要删除这个教师吗？删除后相关数据可能会受到影响。')) {
    return
  }
  
  try {
    const response = await fetch(`/api/teacher/${id}`, { method: 'DELETE' })
    const data = await response.json()
    
    if (response.ok && data.code === 200) {
      alert('教师删除成功')
      fetchTeachers() // 重新获取数据
    } else {
      throw new Error(data.msg || '删除失败')
    }
  } catch (error) {
    alert(`教师删除失败：${error.message}`)
    console.error('教师删除失败:', error)
  }
}
</script>

<style scoped>
/* 导入Font Awesome */
@import url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css');

/* 基础样式 */
.container {
  max-width: 1200px;
  margin: 0 auto;
  position: relative;
}

h1 {
  font-size: 24px;
  color: #333;
}

/* 查询区域样式 */
.query-area {
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

/* 操作栏样式 */
.action-bar {
  display: flex;
  justify-content: flex-end;
}

/* 表格样式 */
.table-container {
  width: 100%;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

.teacher-table {
  width: 100%;
  border-collapse: collapse;
}

.teacher-table th, .teacher-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

.teacher-table th {
  background-color: #f5f5f5;
  font-weight: 600;
  color: #555;
  text-transform: uppercase;
  font-size: 12px;
}

.teacher-table tr:last-child td {
  border-bottom: none;
}

.hover-row:hover {
  background-color: #f9f9f9;
  transition: background-color 0.2s ease;
}

/* 空状态样式 */
.empty-state {
  padding: 40px;
  text-align: center;
}

.empty-icon {
  color: #ccc;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 50;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  max-width: 900px;
  width: 100%;
  transform: scale(0.95);
  transition: transform 0.2s ease;
}

.modal-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.modal-body {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.modal-footer {
  padding: 16px 20px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: flex-end;
}

.modal-content:hover {
  transform: scale(1);
}

/* 表单样式 */
.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 4px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.form-control {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 14px;
  line-height: 20px;
  color: #333;
  background-color: white;
  background-clip: padding-box;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.form-control:focus {
  border-color: #6366f1;
  outline: 0;
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.3);
}

/* 按钮样式 */
button {
  cursor: pointer;
  border: none;
  background-color: transparent;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  transition: background-color 0.2s ease;
}

button:hover {
  opacity: 0.9;
}

button:focus {
  outline: 0;
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.3);
}

.bg-blue-500 {
  background-color: #3b82f6;
  color: white;
}

.bg-green-500 {
  background-color: #22c55e;
  color: white;
}

.bg-red-500 {
  background-color: #ef4444;
  color: white;
}

.bg-gray-50 {
  background-color: #f9fafb;
}

.text-blue-500 {
  color: #3b82f6;
}

.text-green-500 {
  color: #22c55e;
}

.text-red-500 {
  color: #ef4444;
}

.text-purple-600 {
  color: #9333ea;
}

.px-4 {
  padding-left: 1rem;
  padding-right: 1rem;
}

.py-2 {
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
}

.rounded-md {
  border-radius: 0.375rem;
}

/* 错误提示样式 */
.text-red-500 {
  color: #ef4444;
}

.text-sm {
  font-size: 0.875rem;
}

.mt-1 {
  margin-top: 0.25rem;
}

/* 教育经历和家庭关系样式 */
.education-list, .family-list {
  margin-top: 16px;
}

.education-list > div, .family-list > div {
  position: relative;
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 4px;
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
}

/* 状态标签样式 */
.px-2 {
  padding-left: 0.5rem;
  padding-right: 0.5rem;
}

.py-1 {
  padding-top: 0.25rem;
  padding-bottom: 0.25rem;
}

.text-xs {
  font-size: 0.75rem;
}

.font-medium {
  font-weight: 500;
}

.bg-green-100 {
  background-color: #dcfce7;
}

.text-green-800 {
  color: #166534;
}

.bg-yellow-100 {
  background-color: #fef9c3;
}

.text-yellow-800 {
  color: #854d0e;
}

.bg-red-100 {
  background-color: #fee2e2;
}

.text-red-800 {
  color: #991b1b;
}

.bg-gray-100 {
  background-color: #f3f4f6;
}

.text-gray-800 {
  color: #1f2937;
}

.rounded-full {
  border-radius: 9999px;
}

/* 网格布局 */
.grid {
  display: grid;
}

.grid-cols-1 {
  grid-template-columns: repeat(1, minmax(0, 1fr));
}

.grid-cols-2 {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}

.grid-cols-3 {
  grid-template-columns: repeat(3, minmax(0, 1fr));
}

.gap-4 {
  gap: 1rem;
}

.md:grid-cols-2 {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}

.md:grid-cols-3 {
  grid-template-columns: repeat(3, minmax(0, 1fr));
}

.md:col-span-2 {
  grid-column: span 2 / span 2;
}

/* 其他样式 */
.relative {
  position: relative;
}

.absolute {
  position: absolute;
}

.top-2 {
  top: 0.5rem;
}

.right-2 {
  right: 0.5rem;
}

.whitespace-nowrap {
  white-space: nowrap;
}

.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.justify-between {
  justify-content: space-between;
}

.mb-4 {
  margin-bottom: 1rem;
}

.mb-6 {
  margin-bottom: 1.5rem;
}

.inline-block {
  display: inline-block;
}

.w-2 {
  width: 0.5rem;
}

.h-2 {
  height: 0.5rem;
}

.bg-blue-500 {
  background-color: #3b82f6;
}

.bg-green-500 {
  background-color: #22c55e;
}

.bg-purple-500 {
  background-color: #a855f7;
}

.rounded-full {
  border-radius: 9999px;
}

.mr-1 {
  margin-right: 0.25rem;
}

.mr-2 {
  margin-right: 0.5rem;
}

.mr-3 {
  margin-right: 0.75rem;
}

.text-base {
  font-size: 1rem;
}

.font-medium {
  font-weight: 500;
}

.text-gray-900 {
  color: #111827;
}

.hover:bg-gray-50:hover {
  background-color: #f9fafb;
}

.hover:bg-blue-600:hover {
  background-color: #2563eb;
}

.hover:bg-green-600:hover {
  background-color: #16a34a;
}

.hover:bg-red-700:hover {
  background-color: #dc2626;
}

.hover:text-blue-700:hover {
  color: #1d4ed8;
}

.hover:text-green-700:hover {
  color: #15803d;
}

.hover:text-red-700:hover {
  color: #b91c1c;
}

.hover:text-purple-700:hover {
  color: #7e22ce;
}

.transition-colors {
  transition: color 0.2s ease, background-color 0.2s ease;
}
</style>